@page "/app/{AppId}/settings/create-secret-key"

@using System.Text
@using Passwordless.AdminConsole.Components.Pages.App.Settings.SettingsComponents
@using Passwordless.AdminConsole.EventLog.DTOs
@using Passwordless.AdminConsole.EventLog.Loggers
@using Passwordless.AdminConsole.Helpers
@using Passwordless.AdminConsole.Services.PasswordlessManagement
@using Passwordless.Common.Constants
@using Passwordless.Common.EventLog.Enums
@using Passwordless.Common.Models.Apps

@inherits BaseApplicationPage

@inject IPasswordlessManagementClient ManagementClient
@inject IHttpContextAccessor HttpContextAccessor
@inject NavigationManager NavigationManager
@inject IEventLogger EventLogger
@inject ILogger<CreatePublicKey> Logger

<Page Title="Create Secret Key">
    <CreateApiKeyComponent Scopes="@Scopes" OnCreateClicked="@OnCreatedAsync" TScope="SecretKeyScopes" />
</Page>

@code {
    public IReadOnlyCollection<SecretKeyScopes>? Scopes { get; private set; }
    
    public int OrganizationId { get; private set; }

    protected override void OnInitialized()
    {
        Scopes = Enum.GetValues<SecretKeyScopes>().ToArray();
        OrganizationId = HttpContextAccessor.HttpContext!.User.GetOrgId()!.Value;
    }

    public async Task OnCreatedAsync(HashSet<SecretKeyScopes> selectedScopes)
    {
        string? encodedApiKey;
        try
        {
            var request = new CreateSecretKeyRequest(selectedScopes);
            var response = await ManagementClient.CreateApiKeyAsync(AppId, request);

            var eventDto = new OrganizationEventDto(HttpContextAccessor.HttpContext!.Request.HttpContext.User.GetId(),
                EventType.AdminApiKeyCreated,
                $"Created secret key for application {AppId}.",
                Severity.Informational,
                AppId,
                OrganizationId,
                DateTime.UtcNow);
            EventLogger.LogEvent(eventDto);

            encodedApiKey = Base64Url.Encode(Encoding.UTF8.GetBytes(response.ApiKey));
        }
        catch (Exception)
        {
            Logger.LogError("Failed to create secret key for application: {appId}", AppId);
            return;
        }

        await InvokeAsync(() =>
            NavigationManager.NavigateTo($"app/{AppId}/settings/secret-key-created?EncodedApiKey={encodedApiKey}"));
    }
}